package org.simple.web.jwt.handler;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class SimpleAuthenticatingFailureHandler implements AuthenticationFailureHandler, InitializingBean, MessageSourceAware {

    private static ObjectMapper globalObjectMapper = new ObjectMapper();

    static {
        globalObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Map<String, Object> result = new HashMap<>();
        if (e instanceof DisabledException) {
            response.setStatus(HttpStatus.LOCKED.value());
        } else {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        result.put("msg", e.getMessage());
        globalObjectMapper.writeValue(response.getWriter(), result);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(messages, "The message accessor can't be null!");
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messages = new MessageSourceAccessor(messageSource);
    }
}

